package com.study.spring.ch06.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.study.spring.ch06.model.Customer;

@RequestMapping(value = "/ch06") // ①处理器的通用映射前缀
@Controller
public class HelloWorldController {

	@RequestMapping(value = "/validate/showForm", method = RequestMethod.GET)
	public String showForm(Model theModel) {

		theModel.addAttribute("customer", new Customer());
		return "ch06/form";
	}

	/**
	 * "验证类型的注解（如  @Valid） 要放在javabean前面，否则会无法触发JavaBean中的属性 @NotEmpty
	 * 
	 * @param customer
	 * @param theBindingResult
	 * @return
	 */
	@RequestMapping(value = "/validate/processForm")
	public String test3(@ModelAttribute("customer") @Valid Customer customer, BindingResult theBindingResult) {
		if (theBindingResult.hasErrors())
			return "ch06/form";
		return "ch06/success";
	}

	/**
	 * 测试 @ExceptionHandler的触发
	 * @return
	 */
	@RequestMapping("/errorTest/nullTest")
	public String hello1() {
		String a = null;
		a.length();
		return "success";
	}

	/**
	 * 测试 @ExceptionHandler的触发
	 * @return
	 */
	@RequestMapping("/errorTest/arrayIndexOutTest")
	public String hello2() {
		String a[] = { "1" };
		a[1] = "2";
		return "success";
	}

	@ExceptionHandler(value = { NullPointerException.class, ArrayIndexOutOfBoundsException.class })
	public String exceptionExecute(Exception ex, HttpServletRequest request) {
		request.setAttribute("ex", ex);
		if (ex instanceof NullPointerException) {
			// 这里就写如何处理,比如:记日志
			System.out.println("now is NullPointer2");
			return "ch06/errors";
		} else if (ex instanceof ArrayIndexOutOfBoundsException) {
			// 这里就写如何处理,比如:记日志
		}
		return "ch06/error/ArrayIndexOutOfBoundsPage";
	}

}
